#include "StdAfx.h"
#include "vviewmanager.h"
#include "vmodule.h"

#include <QtCore/QDebug>
#include <QtGui/QMenu>
#include <QtGui/QMainWindow>
#include <QtGui/QStackedWidget>
#include <QtGui/QToolBar>

VViewManager::VViewManager(QMenu* modeMenu, QWidget *parent)
	: QObject(parent)
	, m_curView(0)
	, m_modeMenu(modeMenu)
{
	QMainWindow* mw = qobject_cast<QMainWindow*>(parent);
	m_stackWidget = new QStackedWidget(parent);
	mw->setCentralWidget(m_stackWidget);
	m_stackWidget->hide();

	connect(m_modeMenu, SIGNAL(triggered(QAction*)), this, SLOT(activateAction(QAction*)));
}

VViewManager::~VViewManager()
{
	if (m_curView)
		m_curView->deactivate();
}

VAbstractView* VViewManager::activeView() const
{
	return m_curView;
}

void VViewManager::registerView(VAbstractView* view)
{
	if (!view)
		return;

	VViews::const_iterator it = qFind(m_views.begin(), m_views.end(), view);
	
	if (it == m_views.end())
	{
		view->setParent(m_stackWidget);
		m_views.append(view);
		m_stackWidget->addWidget(view);

		if (m_modeMenu)
		{
			QAction* a = m_modeMenu->addAction(view->name());
			m_modeActions[view] = a;
		}
	}	
}

void VViewManager::unregisterView(VAbstractView* view)
{
	m_views.removeOne(view);
	m_stackWidget->removeWidget(view);
}

VAbstractView* VViewManager::findView(const QString& name) const
{
	VAbstractView* view;
	foreach(view, m_views)
		if (view->name() == name)
			return view;

	return 0;
}

void VViewManager::activateAction(QAction* a)
{
	if (!a)
		return;

	QObject* p = parent();
	QMainWindow* mw = qobject_cast<QMainWindow*>(p);
	
	QString name = a->text();
	VAbstractView* view = findView(name);

	if (view)
	{
		if (view == m_curView)
			return;		
		
		if (m_curView)
		{
			foreach(QToolBar* tb, m_curView->toolbar())
				mw->removeToolBar(tb);

			QList<QAction*> actions = m_actions[m_curView];
			for (int i=0; i<actions.count(); ++i)
				mw->menuBar()->removeAction(actions.at(i));

			m_curView->deactivate();
		}
		else
			m_stackWidget->show();

		m_curView = view;
		view->activate();

		foreach(QToolBar* tb, view->toolbar())
			if (tb) mw->addToolBar(tb);

		QList<QAction*> viewAct;
		foreach(QMenu* m, view->menu())
			viewAct.append(mw->menuBar()->addMenu(m));

		m_actions[view] = viewAct;
		m_stackWidget->setCurrentWidget(m_curView);
	}
}

void VViewManager::setActiveView(const QString& name)
{
	if (name.isEmpty())
		return;

	activateAction(m_modeActions[findView(name)]);
}